﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class Configuration_Products_Default : System.Web.UI.Page
{
    private bool Add
    {
        get
        {
            if (ViewState["add"] != null)
            {
                return (bool)ViewState["add"];
            }
            else
            {
                return false;
            }
        }
        set
        {
            ViewState["add"] = value;
        }
    }
    private bool Edit
    {
        get
        {
            if (ViewState["Edit"] != null)
            {
                return (bool)ViewState["Edit"];
            }
            else
            {
                return false;
            }
        }
        set
        {
            ViewState["Edit"] = value;
        }
    }
    private bool View
    {
        get
        {
            if (ViewState["View"] != null)
            {
                return (bool)ViewState["View"];
            }
            else
            {
                return false;
            }
        }
        set
        {
            ViewState["View"] = value;
        }
    }
    private bool Disable
    {
        get
        {
            if (ViewState["Disable"] != null)
            {
                return (bool)ViewState["Disable"];
            }
            else
            {
                return false;
            }
        }
        set
        {
            ViewState["Disable"] = value;
        }
    }
    #region Declare variables to save filters
    private const string _cookieName = "productlist";
    private const string _sortExp = "sortExp";
    private const string _sortDirection = "sortDirection";
    private const string _pageIndex = "pageIndex";
    private const string _filterStatus = "filterStatus";
    private const string _filterSearch = "filterSearch";
    private string sortExp;
    private string SortDirection
    {
        get
        {
            if (Session[_sortDirection] != null)
            {
                return Session[_sortDirection].ToString();
            }
            else
            {
                return "ASC";
            }
        }
        set
        {
            Session[_sortDirection] = value;
        }
    }

    private string SortExp
    {
        get
        {
            if (Session[_sortExp] != null)
                this.sortExp = Session[_sortExp].ToString();
            else
                this.sortExp = "LeadName";
            return (this.sortExp);
        }
        set
        {
            this.sortExp = value;
            Session[_sortExp] = this.sortExp;
        }
    }
    private string PageIndex
    {
        get
        {
            if (Session[_pageIndex] != null)
            {
                return (string)Session[_pageIndex];
            }
            else
            {
                return "0";
            }
        }
        set
        {
            Session[_pageIndex] = value;
        }
    }

    private string FilterStatus
    {
        get
        {
            if (Session[_filterStatus] != null)
            {
                return (string)Session[_filterStatus];
            }
            else
            {
                return "1";
            }
        }
        set
        {
            Session[_filterStatus] = value;
        }
    }

    private string FilterSearch
    {
        get
        {
            if (Session[_filterSearch] != null)
            {
                return (string)Session[_filterSearch];
            }
            else
            {
                return "";
            }
        }
        set
        {
            Session[_filterSearch] = value;
        }
    }
    public bool Recover
    {
        get
        {
            if (ViewState["recover"] == null) return false;
            return (bool)ViewState["recover"];
        }
        set { ViewState["recover"] = value; }
    }
    #endregion
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            SetupPageByUserRoles();
            SetPaginationAndOrderSettings();
        }
        ((Literal)Page.Master.FindControl("ltrShowMessage")).Text = "0";
    }
    private void SetPaginationAndOrderSettings()
    {
        grid.AllowPaging = true;
        grid.AllowSorting = true;
        grid.PageSize = (ConfigurationManager.AppSettings["PageSize"] != null) ? Convert.ToInt32(ConfigurationManager.AppSettings["PageSize"]) : 10;
        grid.PagerSettings.PageButtonCount = (ConfigurationManager.AppSettings["PageButtonCount"] != null) ? Convert.ToInt32(ConfigurationManager.AppSettings["PageButtonCount"]) : 5;
        grid.PagerSettings.FirstPageText = "Primero";
        grid.PagerSettings.LastPageText = "Ultimo";
        grid.PagerSettings.Mode = PagerButtons.NumericFirstLast;
        grid.PagerSettings.Position = PagerPosition.Bottom;
        grid.PagerStyle.CssClass = "pagination";
    }
    protected void grid_RowUpdating(object sender, GridViewUpdateEventArgs e)
    {
        
    }
    protected void grid_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        if (e.CommandName.Equals("AddNew"))
        {
            TextBox txtName = (TextBox)grid.FooterRow.FindControl("txtName");
            TextBox txtDescription = (TextBox)grid.FooterRow.FindControl("txtDescription");
            TextBox txtQuantity = (TextBox)grid.FooterRow.FindControl("txtQuantity");
            CheckBox chkEnabled = (CheckBox)grid.FooterRow.FindControl("chkEnabled");
            DropDownList drpUnit = (DropDownList)grid.FooterRow.FindControl("drpUnit");
            BLLProducts bll = new BLLProducts();
            Product product = new Product();
            product.Name = txtName.Text;
            product.Description = txtDescription.Text;
            product.IsEnabled = chkEnabled.Checked;
            product.CreatedBy = Util.GetCurrentUserId();
            product.Quantity = (drpUnit.SelectedValue == GlobalEnums.Units.kg.ToString() || drpUnit.SelectedValue == GlobalEnums.Units.l.ToString())
                ? (Convert.ToInt32(txtQuantity.Text) * 1000) : Convert.ToInt32(txtQuantity.Text);
            product.Unit = drpUnit.SelectedValue;
            if (bll.InsertProduct(product))
            {
                ((Literal)Page.Master.FindControl("ltrShowMessage")).Text = "1";
                ((Literal)Page.Master.FindControl("ltrMessage")).Text = Resources.Resource.PRODUCT_CREATED;
                ((Literal)Page.Master.FindControl("ltrMessageType")).Text = Resources.Resource.SUCCESS;
            }
            else
            {
                ((Literal)Page.Master.FindControl("ltrShowMessage")).Text = "1";
                ((Literal)Page.Master.FindControl("ltrMessage")).Text = Resources.Resource.UPDATE_ERROR;
                ((Literal)Page.Master.FindControl("ltrMessageType")).Text = Resources.Resource.ERROR;
            }

            grid.DataBind();
        }
        else if (e.CommandName.Equals("UpdateRow"))
        {

            GridViewRow gvr = (GridViewRow)(((ImageButton)e.CommandSource).NamingContainer);
            int RowIndex = gvr.RowIndex;
            TextBox txtName = (TextBox)grid.Rows[RowIndex].FindControl("txtName");
            TextBox txtDescription = (TextBox)grid.Rows[RowIndex].FindControl("txtDescription");
            CheckBox chkEnabled = (CheckBox)grid.Rows[RowIndex].FindControl("chkEnabled");
            int ID = Convert.ToInt32(grid.DataKeys[RowIndex].Values[0].ToString());
            BLLProducts bll = new BLLProducts();
            Product product = new Product();
            product.Name = txtName.Text;
            product.Description = txtDescription.Text;
            product.IsEnabled = chkEnabled.Checked;
            product.Id = ID;
            if(bll.UpdateProduct(product))
            {
                ((Literal)Page.Master.FindControl("ltrShowMessage")).Text = "1";
                ((Literal)Page.Master.FindControl("ltrMessage")).Text = Resources.Resource.PRODUCT_EDITED;
                ((Literal)Page.Master.FindControl("ltrMessageType")).Text = Resources.Resource.SUCCESS;
            }
            else
            {
                ((Literal)Page.Master.FindControl("ltrShowMessage")).Text = "1";
                ((Literal)Page.Master.FindControl("ltrMessage")).Text = Resources.Resource.UPDATE_ERROR;
                ((Literal)Page.Master.FindControl("ltrMessageType")).Text = Resources.Resource.ERROR;
            }
            grid.EditIndex = -1;
            grid.DataBind();
        }
        else if (e.CommandName.Equals("UpdateProductQuantity"))
        {
            GridViewRow gvr = (GridViewRow)(((ImageButton)e.CommandSource).NamingContainer);
            int RowIndex = gvr.RowIndex;
            int ID = Convert.ToInt32(grid.DataKeys[RowIndex].Values[0].ToString());
            this.Response.Redirect("ActualizarProducto.aspx?id="+ID);
        }

    }
    protected void grid_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        this.PageIndex = e.NewPageIndex.ToString();
        setCookie(_pageIndex, this.PageIndex.ToString());
    }

    
    
    protected bool GetBoolValue(string value)
    {
        bool result = false;
        try
        {
            if (value.ToLower() == "true") result = true;
            else result = false;
        }
        catch
        {
        }
        return result;
    }
    protected string GetConfirmValue(string value, string status)
    {
        return "return confirmMessage('Confirmar','Est&aacute; seguro de cambiar el estatus a "+status+"?'," + value + ");";
    }
    #region Sorting
    protected void grid_Sorting(object sender, GridViewSortEventArgs e)
    {
        SetCurrentSortDirection(e.SortExpression);
        this.SortExp = e.SortExpression;
        setCookie(_sortExp, this.SortExp);
        this.PageIndex = "0";
        setCookie(_pageIndex, this.PageIndex);
        this.grid.PageIndex = Convert.ToInt32(this.PageIndex);
    }
    protected void SetCurrentSortDirection(string sExp)
    {

        if (this.SortExp != sExp)
        {
            setCookie(_sortDirection, "ASC");
            this.SortDirection = "ASC";
        }
        else
        {
            if (this.SortDirection == "ASC")
            {
                setCookie(_sortDirection, "DESC");
                this.SortDirection = "DESC";
            }
            else
            {
                setCookie(_sortDirection, "ASC");
                this.SortDirection = "ASC";
            }
        }

    }
    #endregion
    #region Cookies for sorting
    private void Page_Init(object sender, EventArgs e)
    {

        if (this.Page.Request.Cookies[_cookieName] == null)
        {


            HttpCookie cookie = new HttpCookie(_cookieName);
            cookie.Values.Add(_sortExp, "Name");
            cookie.Values.Add(_sortDirection, "ASC");
            cookie.Expires.AddDays(1);
            this.Page.Response.Cookies.Add(cookie);
        }
        else
        {
            bool recover = false;
            if (Request.QueryString["recover"] != null)
                if (Request.QueryString["recover"] != "")
                    if (Request.QueryString["recover"].ToString() == "y")
                    {
                        recover = true;
                        this.Recover = true;
                    }
            if (recover)
            {
                if (this.Page.Request.Cookies[_cookieName][_sortDirection] != null
                    && this.Page.Request.Cookies[_cookieName][_sortDirection] != "")
                    this.SortDirection = this.Page.Request.Cookies[_cookieName][_sortDirection].ToString();
                if (this.Page.Request.Cookies[_cookieName][_sortExp] != null
                    && this.Page.Request.Cookies[_cookieName][_sortExp] != "")
                    this.SortExp = this.Page.Request.Cookies[_cookieName][_sortExp].ToString();
                if (this.Page.Request.Cookies[_cookieName][_filterStatus] != null
                    && this.Page.Request.Cookies[_cookieName][_filterStatus] != "")
                    this.FilterStatus = this.Page.Request.Cookies[_cookieName][_filterStatus].ToString();
                if (this.Page.Request.Cookies[_cookieName][_filterSearch] != null
                    && this.Page.Request.Cookies[_cookieName][_filterSearch] != "")
                    this.FilterSearch = this.Page.Request.Cookies[_cookieName][_filterSearch].ToString();
                if (this.Page.Request.Cookies[_cookieName][_pageIndex] != null
                    && this.Page.Request.Cookies[_cookieName][_pageIndex] != "")
                    this.PageIndex = this.Page.Request.Cookies[_cookieName][_pageIndex].ToString();
                //this.drpStatus.SelectedValue = this.FilterStatus;
                //this.txtSearchTerm.Text = this.FilterSearch;
            }
            else
            {
                if (!IsPostBack)
                {
                    setCookie(_sortDirection, "ASC");
                    setCookie(_sortExp, "Name");
                    setCookie(_filterStatus, "1");
                    setCookie(_filterSearch, "");
                    setCookie(_pageIndex, "0");
                }

            }


        }
        if (!IsPostBack && !this.Recover)
        {
            this.SortDirection = "ASC";
            this.SortExp = "Name";
            this.FilterStatus = "1";
            this.FilterSearch = "";
            this.PageIndex = "0";
        }
        if (this.PageIndex != "" && this.Recover)
            this.grid.PageIndex = Convert.ToInt32(this.PageIndex);
    }

    public void setCookie(string field, string value)
    {
        HttpCookie cookie = this.Page.Request.Cookies.Get(_cookieName);
        cookie.Values.Set(field, value);
        this.Page.Response.Cookies.Add(cookie);
    }
    #endregion
    protected void drpStatus_SelectedIndexChanged(object sender, EventArgs e)
    {
        this.PageIndex = "0";
        setCookie(_pageIndex, this.PageIndex);
        this.grid.PageIndex = Convert.ToInt32(this.PageIndex);
        this.FilterStatus = drpStatus.SelectedValue;
        setCookie(_filterStatus, this.FilterStatus);
    }
    protected void btnSearch_Click(object sender, EventArgs e)
    {
        this.PageIndex = "0";
        setCookie(_pageIndex, this.PageIndex);
        this.grid.PageIndex = Convert.ToInt32(this.PageIndex);
        this.FilterSearch = this.txtSearchTerm.Text.Trim();
        setCookie(_filterSearch, this.FilterSearch);
        grid.DataBind();
    }
    protected void lnkStatus_Click(object sender, EventArgs e)
    {
        BLLProducts bll = new BLLProducts();
        int id = 0;
        int.TryParse(hdnId.Value, out id);
        if(bll.UpdateStatus(id))
        {
            ((Literal)Page.Master.FindControl("ltrShowMessage")).Text = "1";
            ((Literal)Page.Master.FindControl("ltrMessage")).Text = Resources.Resource.PRODUCT_EDITED;
            ((Literal)Page.Master.FindControl("ltrMessageType")).Text = Resources.Resource.SUCCESS;
        }
        else
        {
            ((Literal)Page.Master.FindControl("ltrShowMessage")).Text = "1";
            ((Literal)Page.Master.FindControl("ltrMessage")).Text = Resources.Resource.UPDATE_ERROR;
            ((Literal)Page.Master.FindControl("ltrMessageType")).Text = Resources.Resource.ERROR;
        }
        grid.EditIndex = -1;
        grid.DataBind();
    }
   
    protected void SetupPageByUserRoles()
    {
        List<SessionPermissions> userPermissions = new List<SessionPermissions>();
        userPermissions = (List<SessionPermissions>)Session[GlobalNames.UserPermissions];
        userPermissions = (from upb in userPermissions
                                     where upb.ModuleId == (long)GlobalEnums.Modules.Productos
                                     select upb).ToList();
        if (userPermissions.Count() > 0)
        {
            foreach (SessionPermissions up in userPermissions)
            {
                if (up.PermissionId == (long)GlobalEnums.Permissions.Agregar)
                    Add = true;
                if (up.PermissionId == (long)GlobalEnums.Permissions.Editar)
                    Edit = true;
                if (up.PermissionId == (long)GlobalEnums.Permissions.Ver)
                    this.View = true;
                if (up.PermissionId == (long)GlobalEnums.Permissions.Habilitar_Deshabilitar)
                    this.Disable = true;
            }
            if (!View)
                this.Response.Redirect("~/Default.aspx");
            if (!Add)
                grid.ShowFooter = false;
        }
        else
        {
            this.Response.Redirect("~/Default.aspx");
        }
    }
    protected void grid_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        try
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                if (!Disable)
                {
                    ImageButton ImageButton1 = (ImageButton)e.Row.FindControl("ImageButton1");
                    ImageButton1.Enabled = false;
                    ImageButton1.ToolTip = "";
                    ImageButton ImageButton2 = (ImageButton)e.Row.FindControl("ImageButton2");
                    ImageButton2.Enabled = false;
                    ImageButton2.ToolTip = "";
                }
                if (!Edit)
                {
                    ImageButton imgEdit = (ImageButton)e.Row.FindControl("imgEdit");
                    imgEdit.Enabled = false;
                    imgEdit.ToolTip = "";
                    //ImageButton imgUpdateProduct = (ImageButton)e.Row.FindControl("ImageButton5");
                    //imgUpdateProduct.Enabled = false;
                    //imgUpdateProduct.ToolTip = "";

                }
                double quantity = Convert.ToDouble(DataBinder.Eval(e.Row.DataItem, "Quantity"));
                string unit = DataBinder.Eval(e.Row.DataItem, "Unit").ToString();
                Label lblQuantity = (Label)e.Row.FindControl("lblQuantity");
                lblQuantity.Text = ((quantity > 0) ? ((unit == GlobalEnums.Units.kg.ToString()
                        || unit == GlobalEnums.Units.l.ToString())
                        ? (quantity / 1000).ToString() : quantity.ToString()) : "0") + " " + unit;

            }
        }
        catch { }
        if (grid.Rows.Count == 1 && grid.DataKeys[0].Value.ToString() == "-1")
        {
            grid.Rows[0].Cells[0].ColumnSpan = grid.Rows[0].Cells.Count;
            for (int i = 1; i < grid.Rows[0].Cells.Count; i++)
            {
                grid.Rows[0].Cells[i].Visible = false;

            }
            grid.Rows[0].Cells[0].Text = "No Existen Registros";

        }
    }
}